import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:signage/app/constants/template_constants.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:uuid/uuid.dart';
import 'dart:convert';
import '../../../../widgets/edit_dialog.dart';
import '../../../routes/app_pages.dart';
import '../../../data/models/template_model.dart';
import 'package:flutter/services.dart';

class TemplateController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final allTemplates = <TemplateModel>[].obs;
  final simpleTemplates = <TemplateModel>[].obs;
  final partyTemplates = <TemplateModel>[].obs;
  final agendaTemplates = <TemplateModel>[].obs;
  final myTemplates = <TemplateModel>[].obs;
  final showBackButton = false.obs;

  late TabController tabController;
  final selectedSize = AppLocalizations.of(Get.context!)!.translate('all').obs;
  final editSelectedSize = '7.5 | 800X480'.obs;
  var currentTab = 0.obs;
  @override
  void onInit() async {
    super.onInit();
    tabController = TabController(length: 5, vsync: this);
    tabController.addListener(() {
      currentTab.value = tabController.index;
    });
    final args = Get.arguments;
    if (args != null && args['side'] != null) {
      showBackButton.value = true;
    }
  }

  @override
  void onReady() {
    super.onReady();
    loadTemplates();
  }

  void loadTemplates() {
    if (!Get.context!.mounted) return;

    List<TemplateModel> systemTemplates;

    // 深度复制模板数据
    final templatesCopy = TemplateConstants.defaultTemplates.map((template) {
      return Map<String, dynamic>.from(template).map((key, value) {
        if (value is Map) {
          return MapEntry(key, Map<String, dynamic>.from(value));
        } else if (value is List) {
          return MapEntry(key, List.from(value.map((item) {
            if (item is Map) {
              return Map<String, dynamic>.from(item);
            }
            return item;
          })));
        }
        return MapEntry(key, value);
      });
    }).toList();

    // 使用复制的数据创建模板
    systemTemplates =
        templatesCopy.map((data) => TemplateModel.fromJson(data)).toList();

    // Replace placeholders with localized text
    for (var template in systemTemplates) {
      // Replace template name
      template.name =
          template.name.replaceAllMapped(RegExp(r'\{(\w+)\}(\d*)'), (match) {
        final key = match.group(1) ?? '';
        final number = match.group(2);
        return '${AppLocalizations.of(Get.context!)!.translate(key)}$number';
      });

      // Replace category
      template.category = template.category.replaceAllMapped(
          RegExp(r'\{(\w+)\}'),
          (match) => AppLocalizations.of(Get.context!)!
              .translate(match.group(1) ?? ''));

      // Replace text elements
      for (var element in template.elements) {
        if (element['type'] == 'text' && element['text'] != null) {
          element['text'] = element['text'].toString().replaceAllMapped(
              RegExp(r'\{(\w+)\}'),
              (match) => AppLocalizations.of(Get.context!)!
                  .translate(match.group(1) ?? ''));
        }
      }

//'memberInfos': [
      //   {'keyName': '{name}', 'value': null},
      //   {'keyName': '{company_name}', 'value': null},
      //   {'keyName': '{position_name}', 'value': null},
      // ],
      for (var element in template.memberInfos) {
        if (element.keyName != null && element.keyName!.isNotEmpty) {
          element.keyName = element.keyName.toString().replaceAllMapped(
              RegExp(r'\{(\w+)\}'),
              (match) => AppLocalizations.of(Get.context!)!
                  .translate(match.group(1) ?? ''));
        }
      }
    }

    print('\n=== Final Templates ===');
    for (var template in systemTemplates) {
      print('\nTemplate:');
      print('Name: ${template.name}');
      print('Category: ${template.category}');
      print('Text Elements:');
      for (var element in template.elements) {
        if (element['type'] == 'text') {
          print('- ${element['text']}');
        }
      }
    }
    print('=== End Templates ===\n');

    // 从 SharedPreferences 加载用户模板
    final userTemplatesJson = SpUtil.getString('user_templates') ?? '[]';
    final List<dynamic> userTemplatesData = jsonDecode(userTemplatesJson);
    final userTemplates =
        userTemplatesData.map((data) => TemplateModel.fromJson(data)).toList();

    // 更新所有分类的数据
    allTemplates.value = [...userTemplates, ...systemTemplates]
        .where((t) =>
            t.size == selectedSize.value ||
            selectedSize.value ==
                AppLocalizations.of(Get.context!)!.translate('all'))
        .toList();

    simpleTemplates.value = allTemplates
        .where((t) => t.categoryType == TemplateCategoryType.simple)
        .where((t) =>
            t.size == selectedSize.value ||
            selectedSize.value ==
                AppLocalizations.of(Get.context!)!.translate('all'))
        .toList();

    partyTemplates.value = allTemplates
        .where((t) => t.categoryType == TemplateCategoryType.party)
        .where((t) =>
            t.size == selectedSize.value ||
            selectedSize.value ==
                AppLocalizations.of(Get.context!)!.translate('all'))
        .toList();

    agendaTemplates.value = allTemplates
        .where((t) => t.categoryType == TemplateCategoryType.agenda)
        .where((t) =>
            t.size == selectedSize.value ||
            selectedSize.value ==
                AppLocalizations.of(Get.context!)!.translate('all'))
        .toList();

    myTemplates.value = userTemplates
        .where((t) =>
            t.size == selectedSize.value ||
            selectedSize.value ==
                AppLocalizations.of(Get.context!)!.translate('all'))
        .toList();
  }

  void editTemplate(TemplateModel template) {
    Get.toNamed(Routes.EDIT_TEMPLATE, arguments: {
      "templateId": template.id,
      "templateName": template.name,
      "size": template.size,
    });
  }

  void deleteTemplate(TemplateModel template) {
    myTemplates.remove(template);
    allTemplates.remove(template);
    _saveTemplates();
    update();
  }

  void clickNewTemplate() {
    final TextEditingController controller = TextEditingController();
    if (selectedSize.value !=
        AppLocalizations.of(Get.context!)!.translate('all')) {
      editSelectedSize.value = selectedSize.value;
    } else {
      editSelectedSize.value = '7.5 | 800X480';
    }
    Get.dialog(
      Dialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(16.r),
          ),
          width: 280.w,
          padding: EdgeInsets.all(20.w),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(AppLocalizations.of(Get.context!)!.translate('new_template'),
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              const SizedBox(height: 16),
              TextField(
                decoration: InputDecoration(
                  fillColor: Color(0xFFF7F7F7),
                  filled: true,
                  hintText: AppLocalizations.of(Get.context!)!
                      .translate('enter_template_name'),
                  hintStyle: TextStyle(
                    color: Colors.black38,
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  enabledBorder: InputBorder.none,
                  focusedBorder: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 8.h,
                  ),
                ),
                controller: controller,
                maxLength: 20,
              ),
              const SizedBox(height: 16),
              Obx(() => Row(
                    children: [
                      // 新增下拉选择框
                      PopupMenuButton<String>(
                        elevation: 0,
                        padding: EdgeInsets.zero,
                        constraints: BoxConstraints(
                          minWidth: Get.width,
                          maxHeight: 600.h,
                        ),
                        color: Colors.white,
                        onSelected: (String newValue) {
                          // 处理选择的尺寸
                          editSelectedSize.value = newValue;
                        },
                        position: PopupMenuPosition.under,
                        itemBuilder: (BuildContext context) {
                          return <String>[
                            ...TemplateConstants.deviceScreenSize.entries
                                .map((e) => "${e.value} | ${e.key}")
                          ].map<PopupMenuItem<String>>((String value) {
                            return PopupMenuItem<String>(
                              value: value,
                              child: Row(
                                // 设置宽度为拉满
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(value,
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        color: Color(0XFF333333),
                                      )),
                                  if (value == editSelectedSize.value)
                                    Image.asset(
                                        'assets/images/Group 1321318579@2x.png',
                                        width: 22.w,
                                        height: 22.h),
                                ],
                              ),
                            );
                          }).toList();
                        },
                        offset: Offset(0, 12.h),
                        child: Row(
                          children: [
                            Text(editSelectedSize.value,
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w400,
                                  letterSpacing: 0,
                                  color: Color(0XFF333333),
                                )),
                            8.horizontalSpace,
                            Image.asset('assets/images/Vector@2x (1).png',
                                width: 12.w),
                          ],
                        ), // 显示提示文本
                      ),
                      16.horizontalSpace,
                    ],
                  )),
              const SizedBox(height: 16),
              // 按钮组
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: InkWell(
                      onTap: () => Get.back(),
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(
                            horizontal: 16.w, vertical: 8.h),
                        decoration: BoxDecoration(
                          color: Color(0xFFEFEFEF),
                          borderRadius: BorderRadius.circular(28.r),
                        ),
                        child: Text(
                          AppLocalizations.of(Get.context!)!
                              .translate('cancel'),
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Color(0xFF333333),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        if (controller.text.isNotEmpty) {
                          Get.back();
                          Get.toNamed(Routes.EDIT_TEMPLATE, arguments: {
                            "templateName": controller.text,
                            "size": editSelectedSize.value,
                          });
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(
                            horizontal: 16.w, vertical: 8.h),
                        decoration: BoxDecoration(
                          color: Color(0xFFFCCF01),
                          borderRadius: BorderRadius.circular(28.r),
                        ),
                        child: Text(
                          AppLocalizations.of(Get.context!)!
                              .translate('confirm'),
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Color(0xFF333333),
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  void togglePinTemplate(TemplateModel template) {
    // 更新模板的置顶状态
    final index = allTemplates.indexWhere((t) => t.id == template.id);
    if (index != -1) {
      allTemplates[index].isPinned = !allTemplates[index].isPinned;
    }

    // 同步更新其他列表中的相同模板
    final lists = [
      simpleTemplates,
      partyTemplates,
      agendaTemplates,
      myTemplates,
    ];

    for (var list in lists) {
      final idx = list.indexWhere((t) => t.id == template.id);
      if (idx != -1) {
        list[idx].isPinned = allTemplates[index].isPinned;
      }
    }

    _sortTemplates();
    _saveTemplates();
    update();
  }

  void copyTemplate(TemplateModel template) {
    Get.dialog(TipsDialog(
      title: AppLocalizations.of(Get.context!)!.translate('tips'),
      text:
          AppLocalizations.of(Get.context!)!.translate('confirm_copy_template'),
      onConfirm: () {
        Get.back();
        final newTemplate = TemplateModel(
          id: const Uuid().v4(),
          name: AppLocalizations.of(Get.context!)!
              .translate('template_copy', params: {'name': template.name}),
          width: template.width,
          height: template.height,
          filePath: template.filePath,
          category: template.category,
          categoryType: template.categoryType,
          isPinned: false,
          isSystemTemplate: false,
          size: template.size,
          backgroundColor: template.backgroundColor,
          backgroundImagePath: template.backgroundImagePath,
          memberInfos: template.memberInfos,
          elements: template.elements,
        );

        myTemplates.insert(0, newTemplate);
        allTemplates.insert(0, newTemplate);
        _saveTemplates();
        update();
        myTemplates.refresh();
        allTemplates.refresh();
        ToastUtils.showSuccess(
            AppLocalizations.of(Get.context!)!.translate('template_copied'));
        tabController.index = 4;
      },
    ));
  }

  void renameTemplate(TemplateModel template, String newName) {
    template.name = newName;
    _saveTemplates();
    myTemplates.refresh();
    allTemplates.refresh();
  }

  void _sortTemplates() {
    void sortList(RxList<TemplateModel> list) {
      list.sort((a, b) {
        if (a.isPinned && !b.isPinned) return -1;
        if (!a.isPinned && b.isPinned) return 1;
        // 如果置顶状态相同，保持原有顺序
        return 0;
      });
      // 强制触发列表更新
      list.refresh();
    }

    sortList(allTemplates);
    sortList(simpleTemplates);
    sortList(partyTemplates);
    sortList(agendaTemplates);
    sortList(myTemplates);
  }

  void addTemplate(TemplateModel template) {
    // 添加到我的模板列表
    myTemplates.insert(0, template);
    // 添加到全部模板列表
    allTemplates.insert(0, template);

    // 保存到 SharedPreferences
    _saveTemplates();
    myTemplates.refresh();
    allTemplates.refresh();
  }

  void _saveTemplates() {
    // 只保存用户的模板
    final userTemplatesJson =
        jsonEncode(myTemplates.map((template) => template.toJson()).toList());
    SpUtil.setString('user_templates', userTemplatesJson);

    // 保存系统模板
    final systemTemplatesJson = jsonEncode(allTemplates
        .where((te) => te.isSystemTemplate)
        .map((template) => template.toJson())
        .toList());
    SpUtil.setString('system_templates', systemTemplatesJson);
  }

  void handleTemplateSelection(TemplateModel template) {
    final args = Get.arguments;
    if (args != null && args['side'] != null) {
      // Return selected template to cast view
      Get.back(result: template);
    } else {
      // Normal template editing
      editTemplate(template);
    }
  }

  void removeTemplate(String templateId) {
    allTemplates.removeWhere((template) => template.id == templateId);
  }

  void updateTemplate(TemplateModel template) {
    // 更新全部模板列表
    final allIndex = allTemplates.indexWhere((t) => t.id == template.id);
    if (allIndex != -1) {
      allTemplates[allIndex] = template;
    } else {
      addTemplate(template);
    }

    // 更新我的模板列表
    final myIndex = myTemplates.indexWhere((t) => t.id == template.id);
    if (myIndex != -1) {
      myTemplates[myIndex] = template;
    } else {
      addTemplate(template);
    }

    // 根据分类更新对应的列表
    switch (template.categoryType) {
      case TemplateCategoryType.simple:
        final index = simpleTemplates.indexWhere((t) => t.id == template.id);
        if (index != -1) {
          simpleTemplates[index] = template;
        }
        break;
      case TemplateCategoryType.party:
        final index = partyTemplates.indexWhere((t) => t.id == template.id);
        if (index != -1) {
          partyTemplates[index] = template;
        }
        break;
      case TemplateCategoryType.agenda:
        final index = agendaTemplates.indexWhere((t) => t.id == template.id);
        if (index != -1) {
          agendaTemplates[index] = template;
        }
        break;
    }

    // 刷新所有列表以更新UI
    allTemplates.refresh();
    myTemplates.refresh();
    simpleTemplates.refresh();
    partyTemplates.refresh();
    agendaTemplates.refresh();
  }
}

class TemplateCategoryType {
  static const String simple = 'simple';
  static const String party = 'party';
  static const String agenda = 'agenda';
}
